| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231 |
- import { NextRequest, NextResponse } from 'next/server';
- import { getServerSession } from 'next-auth';
- import { authOptions } from '@/lib/auth';
- import { prisma } from '@/lib/prisma';
- // PUT - Actualizar inscripción de estudiante
- export async function PUT(
- request: NextRequest,
- { params }: { params: Promise<{ id: string }> }
- ) {
- try {
- const session = await getServerSession(authOptions);
-
- if (!session || session.user.role !== 'ADMIN') {
- return NextResponse.json(
- { message: 'No autorizado' },
- { status: 401 }
- );
- }
- const { id } = await params;
- const body = await request.json();
- const { studentId, sectionId, isActive } = body;
- // Validaciones básicas
- if (!studentId || !sectionId) {
- return NextResponse.json(
- { message: 'Estudiante y sección son requeridos' },
- { status: 400 }
- );
- }
- // Verificar si la inscripción existe
- const existingEnrollment = await prisma.studentEnrollment.findUnique({
- where: { id },
- });
- if (!existingEnrollment) {
- return NextResponse.json(
- { message: 'Inscripción no encontrada' },
- { status: 404 }
- );
- }
- // Verificar si el estudiante existe y está activo
- const student = await prisma.student.findFirst({
- where: {
- id: studentId,
- isActive: true,
- deletedAt: null,
- },
- });
- if (!student) {
- return NextResponse.json(
- { message: 'El estudiante seleccionado no existe o no está activo' },
- { status: 400 }
- );
- }
- // Verificar si la sección existe y está activa
- const section = await prisma.section.findFirst({
- where: {
- id: sectionId,
- isActive: true,
- deletedAt: null,
- class: {
- isActive: true,
- deletedAt: null,
- period: {
- isActive: true,
- deletedAt: null,
- },
- },
- },
- include: {
- class: {
- include: {
- period: true,
- },
- },
- },
- });
- if (!section) {
- return NextResponse.json(
- { message: 'La sección seleccionada no existe, no está activa o pertenece a un período inactivo' },
- { status: 400 }
- );
- }
- // Si se está cambiando el estudiante o la sección, verificar duplicados
- if (studentId !== existingEnrollment.studentId || sectionId !== existingEnrollment.sectionId) {
- const duplicateEnrollment = await prisma.studentEnrollment.findFirst({
- where: {
- studentId,
- sectionId,
- isActive: true,
- id: { not: id },
- },
- });
- if (duplicateEnrollment) {
- return NextResponse.json(
- { message: 'El estudiante ya está inscrito en esta sección' },
- { status: 400 }
- );
- }
- }
- // Actualizar la inscripción
- const updatedEnrollment = await prisma.studentEnrollment.update({
- where: { id },
- data: {
- studentId,
- sectionId,
- isActive: isActive !== undefined ? isActive : existingEnrollment.isActive,
- },
- include: {
- student: {
- select: {
- id: true,
- firstName: true,
- lastName: true,
- cedula: true,
- email: true,
- phone: true,
- admissionNumber: true,
- },
- },
- section: {
- select: {
- id: true,
- name: true,
- class: {
- select: {
- id: true,
- name: true,
- code: true,
- period: {
- select: {
- id: true,
- name: true,
- isActive: true,
- },
- },
- },
- },
- },
- },
- },
- });
- return NextResponse.json(updatedEnrollment);
- } catch (error) {
- console.error('Error updating student enrollment:', error);
- return NextResponse.json(
- { message: 'Error interno del servidor' },
- { status: 500 }
- );
- }
- }
- // DELETE - Eliminar inscripción de estudiante
- export async function DELETE(
- request: NextRequest,
- { params }: { params: Promise<{ id: string }> }
- ) {
- try {
- const session = await getServerSession(authOptions);
-
- if (!session || session.user.role !== 'ADMIN') {
- return NextResponse.json(
- { message: 'No autorizado' },
- { status: 401 }
- );
- }
- const { id } = await params;
- // Verificar si la inscripción existe
- const enrollment = await prisma.studentEnrollment.findUnique({
- where: { id },
- });
- if (!enrollment) {
- return NextResponse.json(
- { message: 'Inscripción no encontrada' },
- { status: 404 }
- );
- }
- // Verificar si existen registros de asistencia asociados
- const attendanceCount = await prisma.attendance.count({
- where: {
- studentId: enrollment.studentId,
- section: {
- id: enrollment.sectionId,
- },
- },
- });
- if (attendanceCount > 0) {
- // Si existen registros de asistencia, desactivar en lugar de eliminar
- const deactivatedEnrollment = await prisma.studentEnrollment.update({
- where: { id },
- data: { isActive: false },
- });
- return NextResponse.json({
- message: 'La inscripción ha sido desactivada debido a registros de asistencia existentes',
- enrollment: deactivatedEnrollment,
- });
- } else {
- // Si no hay registros de asistencia, eliminar completamente
- await prisma.studentEnrollment.delete({
- where: { id },
- });
- return NextResponse.json({
- message: 'Inscripción eliminada exitosamente',
- });
- }
- } catch (error) {
- console.error('Error deleting student enrollment:', error);
- return NextResponse.json(
- { message: 'Error interno del servidor' },
- { status: 500 }
- );
- }
- }
|